package main
import (
"fmt"
)
func swap(i, j int) (int, int) {
return j, i
}
func main() {
a := 1
b := 2
a, b = swap(a, b)
fmt.Println("a: ", a)
fmt.Println("b: ", b)
}
等同
a, b = b, a
package main
import (
"fmt"
)
func test() func() int {
return func() int {
return 99
}
}
func main() {
bar := test()
fmt.Printf("%T\n", bar) // %T為型態,印出型態
fmt.Println(bar())
fmt.Println(test()) // 印出test裡的那個function位址
test2 := func(i, j float32) float32 {
return i + j
}
fmt.Printf("%T\n", test2) // %T為型態,印出型態
fmt.Println(test2())
fmt.Println(test2()) // 印出test裡的那個function位址
}
// func() int
// 99
// 0x8dd30
// func(float32, float32) float32
// 23.3
package main
import (
"fmt"
)
func main() {
foo := func() string {
return "Hello go"
}
fmt.Println(foo())
bar := func() {
fmt.Println("hello golang")
}
bar()
func() {
fmt.Println("golang go")
}()
go func(i, j int) {
fmt.Println(i + j)
}(1, 2)
}
package main
import (
"fmt"
"strings"
)
func getUserListSQL(username, email string) string {
sql := "select * from user"
where := []string{}
if username != "" {
where = append(where, fmt.Sprintf("username = '%s'", username))
}
if email != "" {
where = append(where, fmt.Sprintf("email = '%s'", email))
}
return sql + " where " + strings.Join(where, " or ")
}
func main() {
fmt.Println(getUserListSQL("roy", ""))
fmt.Println(getUserListSQL("roy", "roy@gmail.com"))
}
使用struct
package main
import (
"fmt"
"strings"
)
type searchOpts struct {
username string
email string
sex int
}
func getUserListOptsSQL(opts searchOpts) string {
sql := "select * from user"
where := []string{}
if opts.username != "" {
where = append(where, fmt.Sprintf("username = '%s'", opts.username))
}
if opts.email != "" {
where = append(where, fmt.Sprintf("email = '%s'", opts.email))
}
if opts.sex != 0 {
where = append(where, fmt.Sprintf("sex = '%d'", opts.sex))
}
return sql + " where " + strings.Join(where, " and ")
}
func main() {
fmt.Println(getUserListOptsSQL(searchOpts{
username: "roy",
email: "roy@gmail.com",
sex: 1,
}))
}